package com.byls.controller;

import com.byls.dao.NewsMapper;
import com.byls.pojo.News;
import com.byls.repository.NewsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/news")
public class NewsController {
    @Autowired
    private NewsRepository newsRepository;
    @Autowired
    private NewsMapper newsMapper;
    @GetMapping("/findall")
    private List<News> getAll(){
        return newsMapper.getAllNews();
    }
    @GetMapping("/findall/{page}/{size}")
    private Page<News> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        Pageable pageable= PageRequest.of(page-1,size);
        return newsRepository.findAll(pageable);
    }
    @GetMapping("/findbyid/{id}")
    public News findById(@PathVariable("id") Integer id){
        return newsRepository.findById(id).get();
    }
    @PostMapping("/save")//tong guo RequestBody jiang jsonduixiang zhuanwei java duixiang
    public String save(@RequestBody News news){
        News res = newsRepository.save(news);
        if(res!=null){
            return "success";
        }else {
            return "error";
        }
    }
    @PutMapping("/update")
    public String update(@RequestBody News news){
        News res = newsRepository.save(news);
        if(res!=null){
            return "success";
        }else {
            return "error";
        }
    }
    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable("id") int id){
        newsRepository.deleteById(id);
    }

}
